<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { initRouter } from "@/router/utils";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import { getWeiXinQrCode, getWeiXinScanResult } from "@/api/auth";
import { ElMessage } from "element-plus";
import { fa, tr } from "element-plus/es/locale";
defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const dialogVisible = ref(false);
const ruleFormRef = ref<FormInstance>();
//微信登录二维码
const codeUrl = ref("");
const codeId = ref("");
//遮罩层信息
const markInfo = reactive({
  icon: "",
  title: "",
  subTitle: "",
  isShow: false
});
let scanTimer: NodeJS.Timer | null = null;
const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

const ruleForm = reactive({
  username: "admin",
  password: "admin123"
});
//获取微信扫码结果
const getScanResult = () => {
  getWeiXinScanResult({ codeId: codeId.value }).then(res => {
    const scanResult = res.data;
    if (scanResult.isScan) {
      //添加已扫描遮罩层
      markInfo.isShow = true;
      markInfo.title = "已扫描";
      markInfo.icon = "success";
    }
    if (scanResult.isExpire) {
      //二维码已过期,添加刷新按钮遮罩层
      markInfo.isShow = true;
      markInfo.title = "二维码已过期";
      markInfo.subTitle = "点击重新获取二维码";

      markInfo.icon = "error";
      clearInterval(Number(scanTimer));
      return;
    }
    if (scanResult.accessToken !== null && scanResult.refreshToken !== null) {
      //登录成功
      // ElMessage({
      //   showClose: true,
      //   message: "登录成功",
      //   center: true
      // });
      // clearInterval(Number(scanTimer));
    }
  });
};

const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      useUserStoreHook()
        .loginByUsername({ username: ruleForm.username, password: "admin123" })
        .then(res => {
          if (res.success) {
            // 获取后端路由
            initRouter().then(() => {
              router.push("/");
              message("登录成功", { type: "success" });
            });
          }
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
};
//
const openWeiXinDialog = (openFlag: Boolean) => {
  dialogVisible.value = !openFlag;
  if (!openFlag) {
    //打开对话框，获取二维码
    dialogVisible.value = !openFlag;
    getWeiXinQr();
  }
};
const getWeiXinQr = () => {
  getWeiXinQrCode().then(res => {
    if (res.flag) {
      codeUrl.value = res.data.codeUrl;
      codeId.value = res.data.codeId;
      scanTimer = setInterval(() => {
        getScanResult();
      }, 1000);
    }
  });
};

//重新刷新登录二维码
const refreshCode = () => {
  if (markInfo.icon === "error") {
    getWeiXinQr();
    markInfo.isShow = false;
    markInfo.title = "";
    markInfo.subTitle = "";
    markInfo.icon = "";
  }
};
/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>

          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入账号',
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  clearable
                  v-model="ruleForm.username"
                  placeholder="账号"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  clearable
                  show-password
                  v-model="ruleForm.password"
                  placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>
            <Motion>
              <div class="flex">
                <el-button class="w-1/4 flex-1" size="default" type="primary">
                  QQ登录
                </el-button>
                <el-button
                  @click="openWeiXinDialog(dialogVisible)"
                  class="w-1/4 flex-1"
                  size="default"
                  type="success"
                >
                  微信登录
                </el-button>
              </div>
            </Motion>
            <Motion :delay="250">
              <el-button
                class="w-full mt-4"
                size="default"
                type="primary"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                登录
              </el-button>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>

  <el-dialog
    class="!rounded-lg animate__animated animate__backInDown"
    v-model="dialogVisible"
    width="20%"
    center
  >
    <h2 class="text-center text-green-500">微信扫码登陆</h2>
    <div class="code_container">
      <el-image class="!container" :src="codeUrl" />
      <div class="mark" v-show="markInfo.isShow">
        <el-result
          :icon="markInfo.icon"
          :title="markInfo.title"
          :sub-title="markInfo.subTitle"
          @click="refreshCode"
        />
      </div>
    </div>
  </el-dialog>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
.code_container {
  position: relative;
  .mark {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    position: absolute;
    background-color: rgb(255, 255, 254, 0.9);
    z-index: 1;
    transform: translateY(-100%);
  }
}
</style>
